window.CESIUM_BASE_URL = '/Cesium'
// import "./Cesium/Cesium.js";
import dayjs from 'dayjs'

// 测量方式
const MeasurementType = {
  Space: 1, // 空间量算
  Viscidly: 2, // 贴地量算
  CGCS2000: 3,
  XIAN80: 4,
  Planeprojection: 5
}

class Entity {
  #fileName = '/geoJson/'
  #name
  #data
  #attributes = new Map();
  constructor(Name, Viewer, callBack = () => { }, arr = []) {
    if (arr.length > 0) {
      this.#name = Name
      this.#data = new Cesium.CustomDataSource(Name)
      // console.log(this.#data, 'entities.values')
      for (let i = 0; i < arr.length; i++) {
        const properties = Object.entries(arr[i]).map(x => [x[0].toUpperCase(), x[1]])
        // 创建实例并添加到集合entities中
        const entity = this.#data.entities.add({
          name: arr[i].name,
          position: Cesium.Cartesian3.fromDegrees(arr[i].x, arr[i].y),
          billboard: {},
          properties: Object.fromEntries(properties),
          // point: {},
          // label: {},
          // polyline: {},
          // polygon: {}
        })
        // this.#attributes.set(entity.id, arr[i])
      }
      const entities = this.#data.entities.values
      for (let i = 0; i < entities.length; i++) {
        const keyNames = entities[i]._properties._propertyNames
        const entityProperties = {}
        for (let j = 0; j < keyNames.length; j++) {
          entityProperties[keyNames[j]] = entities[i]._properties[keyNames[j]].getValue()
        }
        this.#attributes.set(entities[i].id, entityProperties)
      }
      callBack(this.#data)
      Viewer.dataSources.add(this.#data)
    } else {
      Cesium.GeoJsonDataSource.load(`${this.#fileName}${Name}.json`).then(dataSource => {
        this.#data = dataSource
        // console.log(dataSource, 'entities.values')
        const entities = dataSource.entities.values
        for (let i = 0; i < entities.length; i++) {
          const keyNames = entities[i]._properties._propertyNames
          // console.log(entities[i], 'keyNamesentities[i]')
          const entityProperties = {}
          for (let j = 0; j < keyNames.length; j++) {
            entityProperties[keyNames[j]] = entities[i]._properties[keyNames[j]].getValue()
          }
          this.#attributes.set(entities[i].id, entityProperties)
        }
        // this.attributes
        callBack(dataSource)
        Viewer.dataSources.add(dataSource)
      })
    }
  }

  // 获取属性对象
  get attributes () {
    return this.#attributes
  }

  // 获取实体
  get data () {
    return this.#data
  }

  // 显示隐藏
  set show (b) {
    this.#data.show = b
  }

  // 获取显示隐藏状态
  get show () {
    return this.#data.show
  }

  // 获取属性
  getAttributes (id) {
    return this.#attributes.get(id)
  }
}

class CesiumTool {
  home = {
    position: {
      x: -2917392.7665942605, y: 4786622.488840838, z: 3047995.9805967957
    },
    orientation: { heading: 6.275155332462779, pitch: -0.4187083408549084, roll: 6.283185307179581 }

  }

  home2 = {
    position: {
      x: -2937392.7665942605, y: 4786622.488840838, z: 3047995.9805967957
      // x: -2937392.7665942605, y: 4786622.488840838, z: 3047995.9805967957
    },
    orientation2: { heading: 6.275155332462779, pitch: -0.4187083408549084, roll: 6.283185307179581 }
  }

  #TDT_TOKEN = '0d3ac848dabcc11bf47772c648cb1470' // token
  #viewer // 视口对象
  #type // 风格类型

  #layers // 层列表
  #houseLayer // 房子层
  #layer2d // 2d层

  #ModelLayers = new Map() // 模型层   WSG_POINT  YSG_POINT  HSG_LINE  YSG_LINE  HSG_POINT  WSG_LINE

  #isLoad = false
  // 测量--------

  #isoline

  #lineHeight
  #setHypFlag
  #pickPointEnabled = false

  #handlerDis // 点绘制句柄

  #handlerArea

  #handlerHeight // 绘制句柄
  #clampMode = 0 // 空间模式
  #measurementType = MeasurementType.Space // 测量方式
  // 测量--------
  #entityMap = new Map();

  // 警告
  warningPoint = []

  constructor(container, options = {}, debug = false, type = 3) {
    this.#type = type
    options = {
      geocoder: false,
      homeButton: false,
      sceneModePicker: false,
      baseLayerPicker: false,
      navigationHelpButton: false,
      animation: false,
      timeline: false,
      fullscreenButton: false,
      vrButton: false,
      selectionIndicator: false,
      ...options
    }
    this.#viewer = new Cesium.Viewer(container, options)
    // this.#julianDate = new JulianDate();
    // 修改时间
    this.#viewer.clock.currentTime = new Cesium.JulianDate.fromIso8601('2022-11-29')
    // 去除entity双击事件
    this.#viewer.screenSpaceEventHandler.setInputAction(function () { }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    // // 不使用地形
    // this.#viewer.terrainProvider = new Cesium.TerrainProvider()
    // 关闭光照
    this.#viewer.scene.globe.enableLighting = false
    // 关闭阴影
    this.#viewer.shadows = false
    // 解决地形遮挡entity问题
    this.#viewer.scene.globe.depthTestAgainstTerrain = false
    // var h = viewer.camera.positionCartographic.height; // 当前相机高度
    // 允许相机穿过地形
    this.#viewer.scene.screenSpaceCameraController.enableCollisionDetection = false
    // 显示帧率
    this.#viewer.scene.debugShowFramesPerSecond = debug

    this.#viewer.scene.requestRenderMode = false

    // // 开启泛光
    // this.#viewer.scene.bloomEffect.show = true;
    // // 亮度阈值
    // this.#viewer.scene.bloomEffect.threshold = 1;
    // // 泛光强度
    // this.#viewer.scene.bloomEffect.bloomIntensity = 1;
    // // 开启hdr
    // this.#viewer.scene.hdrEnabled = true;
    // 发光强度调节
    // this.#viewer.scene.bloomEffect.bloomIntensity = 6;
    this.#viewer.scene.globe.baseColor = Cesium.Color.BLACK
    // 天地图
    this.loadTdtMap()
    // 加载服务数据
    this.baseServer()
    // 底图着色修改
    this.mapShader()

    // 加载模型
    this.loadModel()

    // 初始化测量
    this.measureInit()

    // 加载完毕
    this.#isLoad = true
  }

  // 获取加载状态
  get isLoad () {
    return this.#isLoad
  }

  // 获取viewer实例
  get viewer () {
    return this.#viewer
  }

  // 加载服务数据
  baseServer () {
    const self = this
    // // 2d管线
    // const url = 'http://112.102.225.89:7009/iserver/services/map-TaiZhouPipe2D/rest/maps/Pipe2DMap'
    //
    // const originResult = { viewBounds: { top: 28.59477866489464, left: 121.34371057151972, bottom: 28.57280600864464, leftBottom: { x: 121.34371057151972, y: 28.57280600864464 }, right: 121.36568322776972, rightTop: { x: 121.36568322776972, y: 28.59477866489464 } }, viewer: { leftTop: { x: 0, y: 0 }, top: 0, left: 0, bottom: 256, rightBottom: { x: 256, y: 256 }, width: 256, right: 256, height: 256 }, distanceUnit: 'METER', minVisibleTextSize: 0.1, coordUnit: 'DEGREE', scale: 2.7691639957137894E-5, description: '', paintBackground: true, maxVisibleTextSize: 1000, maxVisibleVertex: 36000000, clipRegionEnabled: false, antialias: false, textOrientationFixed: false, angle: 0, prjCoordSys: { distanceUnit: 'METER', projectionParam: null, epsgCode: 4326, coordUnit: 'DEGREE', name: 'GCS_WGS_1984', projection: null, type: 'PCS_EARTH_LONGITUDE_LATITUDE', coordSystem: { datum: { name: 'D_WGS_1984', type: 'DATUM_WGS_1984', spheroid: { flatten: 0.0033528106647474805, name: 'WGS_1984', axis: 6378137, type: 'SPHEROID_WGS_1984' } }, unit: 'DEGREE', spatialRefType: 'SPATIALREF_EARTH_LONGITUDE_LATITUDE', name: 'GCS_WGS_1984', type: 'GCS_WGS_1984', primeMeridian: { longitudeValue: 0, name: 'Greenwich', type: 'PRIMEMERIDIAN_GREENWICH' } } }, minScale: 0, markerAngleFixed: false, overlapDisplayedOptions: { allowPointWithTextDisplay: true, horizontalOverlappedSpaceSize: 0, allowPointOverlap: true, allowThemeGraduatedSymbolOverlap: false, verticalOverlappedSpaceSize: 0, allowTextOverlap: false, allowThemeGraphOverlap: false, allowTextAndPointOverlap: true }, visibleScales: [3.3803271432053105E-9, 6.760654286410621E-9, 1.3521308572821242E-8, 2.7042617145642484E-8, 5.408523429128497E-8, 1.0817046858256994E-7, 2.1634093716513982E-7, 4.3268187433027964E-7, 8.653637486605593E-7, 1.7307274973211186E-6, 3.461454994642237E-6, 6.922909989284474E-6, 1.3845819978568949E-5, 2.7691639957137897E-5, 5.5383279914275794E-5, 1.1076655982855159E-4, 2.2153311965710318E-4, 4.4306623931420646E-4, 8.861324786284129E-4], dpi: 96, visibleScalesEnabled: true, customEntireBoundsEnabled: false, clipRegion: { center: null, parts: null, style: null, prjCoordSys: null, id: 0, type: 'REGION', partTopo: null, points: null }, maxScale: 1.0E12, customParams: '', center: { x: 121.35469689964472, y: 28.58379233676964 }, dynamicPrjCoordSyses: [{ distanceUnit: null, projectionParam: null, epsgCode: 0, coordUnit: null, name: null, projection: null, type: 'PCS_ALL', coordSystem: null }], colorMode: 'DEFAULT', textAngleFixed: false, overlapDisplayed: false, userToken: { userID: '' }, cacheEnabled: true, dynamicProjection: true, autoAvoidEffectEnabled: true, customEntireBounds: null, name: 'Pipe2DMap', bounds: { top: 28.625985286423788, left: 121.30642002304927, bottom: 28.51263757005522, leftBottom: { x: 121.30642002304927, y: 28.51263757005522 }, right: 121.43232809385584, rightTop: { x: 121.43232809385584, y: 28.625985286423788 } }, backgroundStyle: { fillGradientOffsetRatioX: 0, markerSize: 2.4, fillForeColor: { red: 255, green: 255, blue: 255, alpha: 255 }, fillGradientOffsetRatioY: 0, markerWidth: 0, markerAngle: 0, fillSymbolID: 0, lineColor: { red: 0, green: 0, blue: 0, alpha: 255 }, markerSymbolID: 0, lineWidth: 0.1, markerHeight: 0, fillOpaqueRate: 100, fillBackOpaque: true, fillBackColor: { red: 255, green: 255, blue: 255, alpha: 255 }, fillGradientMode: 'NONE', lineSymbolID: 0, fillGradientAngle: 0 } }
    // const visibleScales = originResult.visibleScales
    // const min = this.findNearScale(visibleScales[0])
    // const max = this.findNearScale(visibleScales[visibleScales.length - 1])
    // const provider = new Cesium.SuperMapImageryProvider({
    //   url,
    //   name: '管线',
    //   // 设置最大缩放层级后，到了最大缩放层级，不会去后端请求数据，但是地图还可以继续放大
    //   maximumLevel: max,
    //   minimumLevel: min
    // })
    // this.#layer2d = this.#viewer.imageryLayers.addImageryProvider(provider, 10)

    // 建筑群
    const promise = this.#viewer.scene.open(window.LINEURLINFO.MODELURL)
    Cesium.when.all(promise, function (layers) {
      const hyps = new Cesium.HypsometricSetting()
      // 创建分层设色对象
      var colorTable = new Cesium.ColorTable()
      // 设置最大/最小可见高度， 颜色表
      colorTable.insert(0, new Cesium.Color(0, 39 / 255, 148 / 255))
      colorTable.insert(55, new Cesium.Color(149 / 255, 232 / 255, 249 / 255))
      hyps.ColorTable = colorTable
      hyps.Opacity = 0.8// 透明度
      hyps.LineInterval = 10.0// 线宽
      layers[0].hypsometricSetting = {
        hypsometricSetting: hyps,
        analysisMode: Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_ALL // 显示模式
      }
      layers[0].visible = false
      self.#houseLayer = layers[0]
    })
  }

  // 加载模型
  loadModel () {
    const self = this
    const model = this.#viewer.scene.open(window.LINEURLINFO.LINEURL)
    window.module = model
    // 设置模型

    Cesium.when(model, function (dataSource) {
      // 设置模型的显示属性
      dataSource.forEach(item => {
        // console.log(item, '>>>>>>>>>')
        // item._style3D._fillForeColor.alpha = 0.1
        item.visible = false

        self.#ModelLayers.set(item.name, item)
      })
      // 设置相机位置、视角，便于观察场景
      if (!this.#viewer.scene.pickPositionSupported) {
        alert('不支持深度纹理,无法拾取位置！')
      }
    }, function () {

    })
    // Cesium.loadJson('http://112.102.225.89:7009/iserver/services/3D-TaiZhouPipe3DMap/rest/realspace/scenes.json')
  }

  // 模型层显示控制
  showModel (name, visible = true, i = 5) {
    if (i == 0) { return; } else { i-- };
    if (this.#ModelLayers.has(name)) {
      console.log(name)
      this.#ModelLayers.get(name).visible = visible
    } else {
      setTimeout(() => {
        this.showModel(name, visible, i)
      }, 4000);
      // console.log(this.#ModelLayers.get(name))
      // console.log("失败！！！！");
    }
  }

  // 获取管线层显示状态
  getModelShow (name) {
    return this.#ModelLayers.get(name).visible
  }

  // 建筑层控制
  showHouse (visible = true) {
    if (this.#houseLayer) this.#houseLayer.visible = visible
  }

  // 2d层显示控制
  show2dLayer (visible = true) {
    if (this.#layer2d) this.#layer2d.show = visible
  }

  // webGL3D采用固定比例尺出图，且从第一级比例尺开始。
  findNearScale (scale) {
    // webGL3D采用固定比例尺出图，且从第一级比例尺开始。
    let indexScale = 3.3803271432053056E-9
    let sub
    let zoom = 0
    for (let j = 0; j < 20; j++) {
      const temp = window.Math.abs(scale - indexScale)
      if (j === 0) {
        sub = temp
        indexScale = indexScale * 2
        continue
      }
      if (sub > temp) {
        sub = temp
        zoom = j
      } else {
        break
      }
      indexScale = indexScale * 2
    }
    return zoom
  }

  // 天地图服务
  loadTdtMap () {
    // 天地图
    const imgImagery = new Cesium.TiandituImageryProvider({
      mapStyle: Cesium.TiandituMapsStyle.VEC_C, // 天地图全球中文注记服务（经纬度投影）
	    maximumLevel: 17,
      token: this.#TDT_TOKEN,

    })

    // 初始化天地图全球中文注记服务，并添加至影像图层
    const labelImagery = new Cesium.TiandituImageryProvider({
      mapStyle: Cesium.TiandituMapsStyle.CIA_C, // 天地图全球中文注记服务（经纬度投影）
	    maximumLevel: 17,
      token: this.#TDT_TOKEN
    })

    const img = this.#viewer.imageryLayers.addImageryProvider(imgImagery)
    this.#viewer.imageryLayers.addImageryProvider(labelImagery)

    window.imgMap = img
    if (Number(this.#type) === 1) {
      img.brightness = 0.9 // 亮度1
      img.saturation = 0.2 // 饱和度1
      img.gamma = 0.8 // 伽马1
    }

  }

  // 更改地图着色器代码
  mapShader () {
    /* 修改颜色 */
    // const baseLayer = viewer.imageryLayers.get(0)
    // 设置两个变量，用来判断是否进行颜色的翻转和过滤
    let color = [125, 205, 185]
    switch (Number(this.#type)) {
      case 1:
        color = [0, 255, 255]
        break
      case 2:
        color = [255, 255, 255]
        break
    }
    const options = {
      invertColor: true,
      filterRGB: color

    }

    const baseFragShader = (this.#viewer.scene.globe)._surfaceShaderSet.baseFragmentShaderSource.sources
    for (let i = 0; i < baseFragShader.length; i++) {
      // console.log(baseFragShader[i])
      // console.log('------')

      const strS = 'color = czm_saturation(color, textureSaturation);\n#endif\n'
      let strT = 'color = czm_saturation(color, textureSaturation);\n#endif\n'
      if (options.invertColor) {
        // strT += `
        //   color.r = 1.0 - color.r*0.9;
        //   color.g = 1.0 - color.g*0.4;
        //   color.b = 1.0 - color.b*0.8;
        //   `
        strT += `
                  color.r = 1.0 - color.r;
                  color.g = 1.0 - color.g*0.95;
                  color.b = 1.0 - color.b*0.85;
                  `
      }
      if (options.filterRGB.length > 0) {
        strT += `
                  color.r = color.r * ${options.filterRGB[0]}.0/255.0;
                  color.g = color.g * ${options.filterRGB[1]}.0/255.0;
                  color.b = color.b * ${options.filterRGB[2]}.0/255.0;
                  `
      }
      baseFragShader[i] = baseFragShader[i].replace(strS, strT)
    }
  }

  // 测量相关------------
  // 初始化测量
  measureInit () {
    const self = this
    // 等高线
    this.#isoline = new Cesium.HypsometricSetting()
    this.#isoline.DisplayMode = Cesium.HypsometricSettingEnum.DisplayMode.LINE
    const colorTable = new Cesium.ColorTable()

    this.#isoline._lineColor = Cesium.Color.fromCssColorString('#ff7d00')
    this.#isoline.ColorTable = colorTable
    this.#isoline.Opacity = 0.6
    this.#isoline.MaxVisibleValue = -100
    this.#isoline.MinVisibleValue = -100
    this.#layers = this.#viewer.scene.layers.layerQueue

    this.#viewer.scene.globe.HypsometricSetting = {
      hypsometricSetting: this.#isoline,
      analysisMode: Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_ALL
    }

    // 初始化测量距离
    this.#handlerDis = new Cesium.MeasureHandler(this.#viewer, Cesium.MeasureMode.Distance, this.#clampMode)

    // 注册测距功能事件
    this.#handlerDis.measureEvt.addEventListener(function (result) {
      let dis = Number(result.distance)
      const selOptV = self.#measurementType
      const positions = result.positions
      if (selOptV === MeasurementType.CGCS2000 || selOptV === MeasurementType.XIAN80) dis = Number(self.calcClampDistance(positions))
      const distance = dis > 1000 ? (dis / 1000).toFixed(2) + 'km' : dis.toFixed(2) + 'm'
      self.#handlerDis.disLabel.text = '距离:' + distance
    })
    this.#handlerDis.activeEvt.addEventListener(function (isActive) {
      if (isActive == true) {
        self.#viewer.enableCursorStyle = false

        self.#viewer._element.style.cursor = ''
        self.#viewer.scene.pickPointEnabled = self.#pickPointEnabled
      } else {
        self.#viewer.enableCursorStyle = true
        self.#viewer.scene.pickPointEnabled = false
      }
    })

    // 初始化测量面积
    this.#handlerArea = new Cesium.MeasureHandler(this.#viewer, Cesium.MeasureMode.Area, this.#clampMode)
    this.#handlerArea.measureEvt.addEventListener(function (result) {
      let mj = Number(result.area)
      const selOptV = self.#measurementType
      const positions = result.positions
      if (selOptV === MeasurementType.CGCS2000 || selOptV === MeasurementType.XIAN80) {
        mj = Number(self.calcClampValue(positions))
      }
      // else if (selOptV == MeasurementType.Planeprojection) {
      //     mj = Number(self.calcAreaWithoutHeight(positions));
      // }

      const area = mj > 1000000 ? (mj / 1000000).toFixed(2) + 'km²' : mj.toFixed(2) + '㎡'
      self.#handlerArea.areaLabel.text = '面积:' + area
    })
    this.#handlerArea.activeEvt.addEventListener(function (isActive) {
      if (isActive == true) {
        self.#viewer.enableCursorStyle = false

        self.#viewer._element.style.cursor = ''
        self.#viewer.scene.pickPointEnabled = self.#pickPointEnabled
      } else {
        self.#viewer.enableCursorStyle = true
        self.#viewer.scene.pickPointEnabled = false
      }
    })
  }

  // 初始化设置图层等高线
  setHypsometricSetting () {
    for (let i = 0; i < this.#layers.length; i++) {
      this.#layers[i].hypsometricSetting = {
        hypsometricSetting: this.#isoline,
        analysisMode: Cesium.HypsometricSettingEnum.AnalysisRegionMode.ARM_ALL
      }
    }
    this.#setHypFlag = true
  }

  // 椭球贴地距离
  calcClampDistance (positions) {
    const lonlat = []
    let value = 0
    for (let i = 0; i < positions.length; i++) {
      const cartographic = Cartographic.fromCartesian(positions[i])
      const lon = Cesium.Math.toDegrees(cartographic.longitude)

      const lat = Cesium.Math.toDegrees(cartographic.latitude)
      lonlat.push(lon, lat)
    }

    const gemetry = new PolylineGeometry({

      positions: Cartesian3.fromDegreesArray(lonlat)
    })

    const selOptV = this.#measurementType
    if (selOptV == MeasurementType.CGCS2000) {
      value = globe.computeSurfaceDistance(gemetry, Ellipsoid.CGCS2000)
    } else if (selOptV == MeasurementType.XIAN80) {
      value = scene.globe.computeSurfaceDistance(gemetry, Ellipsoid.XIAN80)
    }
    return value
  }

  // 椭球贴地面积
  calcClampValue (positions) {
    const lonlat = []
    let value = 0
    for (let i = 0; i < positions.length; i++) {
      const cartographic = Cartographic.fromCartesian(positions[i])
      const lon = Cesium.Math.toDegrees(cartographic.longitude)

      const lat = Cesium.Math.toDegrees(cartographic.latitude)
      lonlat.push(lon, lat)
    }

    const gemetry = new PolygonGeometry.fromPositions({

      positions: Cartesian3.fromDegreesArray(lonlat)
    })

    const selOptV = this.#measurementType
    if (selOptV == 3) {
      value = this.#viewer.scene.globe.computeSurfaceArea(gemetry, Ellipsoid.CGCS2000)
    } else if (selOptV == 4) {
      value = this.#viewer.scene.globe.computeSurfaceArea(gemetry, Ellipsoid.XIAN80)
    }
    return value
  }

  // 测距
  measuringDistance () {
    this.deactiveAll()
    this.#handlerDis && this.#handlerDis.activate()
  }

  // 测面
  measuringSurface () {
    this.deactiveAll()
    this.#handlerArea && this.#handlerArea.activate()
  }

  // 清除绘制信息
  deactiveAll () {
    this.#handlerDis && this.#handlerDis.deactivate()
    this.#handlerArea && this.#handlerArea.deactivate()
    this.#handlerHeight && this.#handlerHeight.deactivate()
    this.#lineHeight = -10000
  }

  // 清除所有绘制
  clearAll () {
    this.deactiveAll()
    this.#handlerDis && this.#handlerDis.clear()
    this.#handlerArea && this.#handlerArea.clear()
    this.#handlerHeight && this.#handlerHeight.clear()
    this.updateContourLine()
  }

  //   设置等值线
  updateContourLine (height = -10000) {
    this.#viewer.scene.globe.HypsometricSetting.hypsometricSetting.MaxVisibleValue = height
    this.#viewer.scene.globe.HypsometricSetting.hypsometricSetting.MinVisibleValue = height
    if (!this.#setHypFlag) return
    for (let i = 0; i < this.#layers.length; i++) {
      if (this.#layers[i].hypsometricSetting.hypsometricSetting) {
        this.#layers[i].hypsometricSetting.hypsometricSetting.MaxVisibleValue = height
        this.#layers[i].hypsometricSetting.hypsometricSetting.MinVisibleValue = height
      } else {
        this.setHypsometricSetting()
      }
    }
  };

  // 测量相关------------
  // 漫游点  [{data: 实体, time: 时长}]
  flyToArr (arr) {
    const point = arr.pop()
    if (point) {
      this.#viewer.flyTo(point.data, {
        duration: point.time
      }).then(t => {
        if (t) this.flyToArr(arr)
      })
    }
  }

  // 回到路桥区
  goHome (time = 1.5) {
    // 设置相机位置
    this.#viewer.camera.flyTo({
      // 设置相机位置
      destination: this.home.position,
      orientation: this.home.orientation,
      duration: time
    })
  }

  // 回到路桥区
  goHome2 (time = 1.5) {
    // 设置相机位置
    this.#viewer.camera.flyTo({
      // 设置相机位置
      destination: this.home2.position,
      orientation: this.home2.orientation2,
      duration: time
    })
  }

  // 获取相机状态
  getCameraStatus () {
    console.log(this.#viewer.camera)
  }

  // 缩放
  zoom (size = 2) {
    // viewer 为 Viewer 对象
    const position = this.#viewer.camera.position
    const cameraHeight = this.#viewer.scene.globe.ellipsoid.cartesianToCartographic(position).height
    // 每次缩小 20 倍，参数可改
    const moveRate = cameraHeight / 20.0
    if (size > 0) {
      this.#viewer.camera.moveForward(moveRate)
      // this.#viewer.camera.zoomIn(size)
    } else {
      this.#viewer.camera.moveBackward(moveRate)
      // this.#viewer.camera.zoomOut(size)
    }
  }

  // 三位坐标转屏幕坐标
  canvasPoint (position) {
    return Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height)
  }

  // 事件注册
  event (func, eventType = Cesium.ScreenSpaceEventType.LEFT_CLICK) {
    const self = this
    // http://support.supermap.com.cn:8090/webgl/docs/Documentation/ScreenSpaceEventHandler.html?classFilter=ScreenSpaceEventHandler
    // 事件类型 http://support.supermap.com.cn:8090/webgl/docs/Documentation/ScreenSpaceEventType.html?classFilter=ScreenSpaceEventType
    const handler = new Cesium.ScreenSpaceEventHandler(this.#viewer.scene.canvas)
    handler.setInputAction(func, eventType)
    return handler
  }

  // geo数据显示控制
  loadGeoEntity (Name, Show, callback = () => { }, arr = []) {
    // console.log(arr,">>>>>>>>>>>>>")
    if (this.#entityMap.has(Name)) {
      this.#entityMap.get(Name).show(Show)
    } else {
      this.#entityMap.set(Name, new Entity(Name, this.#viewer, data => {
        data.show = Show
        callback(data)
      }, arr.length > 0 ? arr : []))
    }
  }

  // 获取geojson对象map
  get entitys () {
    return this.#entityMap
  }

  // 获取天地图token
  get tdtToekn () {
    return this.#TDT_TOKEN
  }
}



const time = dayjs('2023-12-04').unix()
if (time <= dayjs(new Date()).unix()) {
  console.clear()
  console.log('---------过期了-------')
  window.CesiumTool = null
} else {
  window.CesiumTool = CesiumTool;
}

// 压缩不能使用export default，先挂载到window上，压缩完再导出


export default CesiumTool;

// window.onload = function () {
//     window.cesium = new CesiumTool('map', {}, true);
//     // window.cesium.event(function (e) {
//     //     let pick = window.cesium.viewer.scene.pick(e.position);
//     //     console.log(e, pick, '----------------');
//     // });
//     // window.cesium.loadGeoEntity("河道", true, function (dataSource) {
//     //     dataSource.entities.values.forEach(function (entity) {
//     //         entity.polygon.material = Cesium.Color.RED.withAlpha(0.5);
//     //         entity.polygon.outline = false;
//     //     });
//     // });
//     // window.cesium.goHome();
// }

// #entityMap //geoJosn数据

// 测量 ---------
// 测距               measuringDistance
// 测面               measuringSurface
// 清除所有绘制           clearAll
// 定位--------------
// 回到路桥区            getHome(number=飞行时间)
// 缩放                 zoom(number=缩放倍数)

// 场景坐标转屏幕坐标        canvasPoint(entity.position)
// 事件注册             event(func=Funtion, eventType = 枚举（事件类型）)
// 加载geo数据            loadGeoEntity(name='文件名', show=true/false)
